/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author wpc
 */
public class Analyzer {

    public static double[] lossRate(List<Long> rateList){
        double mean = 0;
        List<Double> lossRateList = new ArrayList<Double>(rateList.size());
        for(Long loss:rateList){
            double rate = loss*1.0/Utils.BATCH_SIZE;
            lossRateList.add(rate);
            mean += rate;
        }
        mean /= rateList.size();
        double[] res = {mean, ci(lossRateList,mean),(double)rateList.size()};
        return res;
   }

   public static double[] queueDelay(List<Double> delayList){
     double m = mean(delayList);
     double[] res = {m, ci(delayList, m),(double)delayList.size()};
     return res;
   }

   public static Map<Integer, Double[]> delayTimes(Map<Integer, List<Double>> delayBatchMap){
       Map<Integer, Double[]> resMap = new HashMap<Integer, Double[]>();
       for(Integer i:delayBatchMap.keySet()){
           List<Double> list = delayBatchMap.get(i);
           double m = mean(list);
           Double[] res = {m, ci(list,m), (double)list.size()};
           resMap.put(i, res);
       }
       return resMap;
   }

   private static double mean(List<Double> list){
       double m = 0;
       for(Double d:list)
           m+=d;
       return m/list.size();
   }

   private static double ci(List<Double> list, double mean){
       double var = 0;
       for(Double item:list){
          double a = item-mean;
          a *=a;
          var += a;
       }
       var /= (list.size()-1);
       var = Math.sqrt(var);
       double interval = getN(list.size())*var/Math.sqrt(list.size());
       return interval;
   }

   private static double getN(int batch){
     double n =1.95996;
     if (batch <=30)
       n = 2.04227;
     if (batch <=25)
       n = 2.05954;
     if (batch <=20)
       n = 2.08596;
     if (batch <=15)
       n = 2.13145;
     if (batch <=10)
       n = 2.22814;
     if (batch <=5)
       n = 2.57058;

     if (batch <= 4)
       n = 2.77645;
     if (batch <= 3)
       n = 3.18245;
     if (batch <= 2)
       n = 4.30265;
     if (batch <= 1)
       n = 12.70620;
     return n;
   }

}
